package cn.dansj.common.utils.spring.request;

import java.io.IOException;
import java.io.InputStream;

import cn.dansj.common.utils.io.IOUtils;
import cn.dansj.common.utils.lang.Nullable;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.MultiValueMap;

final class HttpComponentsClientHttpResponse implements ClientHttpResponse {
    private final ClassicHttpResponse httpResponse;
    @Nullable
    private HttpHeaders headers;

    HttpComponentsClientHttpResponse(ClassicHttpResponse httpResponse) {
        this.httpResponse = httpResponse;
    }

    @Override
    public HttpStatus getStatusCode() {
        return HttpStatus.valueOf(this.httpResponse.getCode());
    }

    @Override
    public int getRawStatusCode() {
        return this.httpResponse.getCode();
    }

    @Override
    public String getStatusText() {
        return this.httpResponse.getReasonPhrase();
    }

    @Override
    public HttpHeaders getHeaders() {
        if (this.headers == null) {
            MultiValueMap<String, String> adapter = new HttpComponentsHeadersAdapter(this.httpResponse);
            this.headers = HttpHeaders.readOnlyHttpHeaders(adapter);
        }
        return this.headers;
    }

    @Override
    public InputStream getBody() throws IOException {
        HttpEntity entity = this.httpResponse.getEntity();
        return (entity != null ? entity.getContent() : IOUtils.nullInputStream());
    }

    @Override
    public void close() {
        try {
            try {
                EntityUtils.consume(this.httpResponse.getEntity());
            } finally {
                this.httpResponse.close();
            }
        } catch (IOException ex) {
            // Ignore exception on close...
        }
    }
}
